//
//  ObservableExtension.swift
//  33web
//
//  Created by 宋海胜 on 2020/12/4.
//

import HandyJSON
import RxSwift

//数据映射错误
public enum RxMapModelError: Error {
    case parsingError
}

//扩展Observable：增加模型映射方法
public extension Observable where Element:Any {
    
    //将JSON数据转成对象
    public func mapModel<T>(type:T.Type) -> Observable<T> where T:HandyJSON {
        return self.map { (element) -> T in
            guard let parsedElement = T.deserialize(from: element as? Dictionary) else {
                throw RxMapModelError.parsingError
            }
            
            return parsedElement
        }
    }
    
    //将JSON数据转成数组
    public func mapModels<T>(type:T.Type) -> Observable<[T]> where T:HandyJSON {
        return self.map { (element) -> [T] in
            guard let parsedArray = [T].deserialize(from: element as? [Any]) else {
                throw RxMapModelError.parsingError
            }
            
            return parsedArray as! [T]
        }
    }
}
